const { mysql, pool, Result, Myquery } = require('../connect');
const express = require('express')
const router = express.Router()

router.post('/',(req,res)=>{
	new insertPhone(req,res);
})

router.get('/',(req,res)=>{
	new insertPhone(req,res);
})

router.get('/navigate',(req,res)=>{
	res.send("<a href='/login/navigate'>login-navigate</a><br/><a href='/userinfo/navigate'>userinfo-navigate</a>")
})

// 插入数据
function insertPhone(req,res) {
	var phone = req.params.phone || req.query.phone || req.body.phone;
	console.log(phone)
	var myreg = /^[1][0-9][0-9]{9}$/;
	var msg = '成功';
    if (!phone) {
      	msg = '请输入手机号'
		res.json(new Result({code:-1,msg:msg}))
    } else if (!myreg.test(phone)) {
      	msg = '请输入正确的11位手机号'
		res.json(new Result({code:-2,msg:msg}))
    }else {
    	selectRepeat(phone,res)
    	.then(()=> {
    		var sql = "INSERT INTO `user_info` (`phone`) VALUES ( ? )"
			var inserts = [phone]
			sql = mysql.format(sql, inserts)
			console.log(sql)
			
		    new Myquery(sql,(err,r)=>{
				if (err) throw err;
				res.json(new Result({msg:msg}))
		    })
    	},()=>{
    		msg = '该号码已存在，请重新输入'
    		res.json(new Result({code:-3,msg:msg}))
    	})
    	
    }	
}

// 查重
function selectRepeat(phone,res) {
	return new Promise((resolve,reject)=>{
		var sql = "SELECT * FROM `user_info` WHERE phone = ? ";
		var inserts = [phone]
		sql = mysql.format(sql, inserts)

		new Myquery(sql,(err,r)=>{
			if (err) throw err;
			if(r.length>0) {
				reject();
			}else {
				resolve();
			}
	    })
	})
	
}

module.exports = router;